package de.slothsoft.commons.swing.util;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;

public abstract class WindowUtil {

	public static void centerWindow(Window window) {
		Toolkit tk = Toolkit.getDefaultToolkit();
		Dimension size = tk.getScreenSize();
		centerWindowOnRectangle(window, size.width, size.height);
	}

	public static void centerWindowOnParent(Window window) {
		centerWindowOnParent(window, window.getParent());
	}

	public static void centerWindowOnParent(Window window, Component component) {
		Dimension size = component.getSize();
		Point location = component.getLocation();
		centerWindowOnRectangle(window, size.width, size.height, location.x,
				location.y);
	}

	public static void centerWindowOnRectangle(Window window, int width,
			int height) {
		centerWindowOnRectangle(window, width, height, 0, 0);
	}

	public static void centerWindowOnRectangle(Window window, int width,
			int height, int offsetX, int offsetY) {

		Dimension windowSize = window.getSize();
		int windowHeight = windowSize.height;
		int windowWidth = windowSize.width;

		int x = offsetX + (width - windowWidth) / 2;
		int y = offsetY + (height - windowHeight) / 2;

		window.setLocation(x, y);
	}

	public static Window getWindow(Component component) {
		Component parent = component.getParent();
		if (parent == null) {
			return null;
		}
		if (parent instanceof Window) {
			return (Window) parent;
		}
		return getWindow(parent);
	}

	private WindowUtil() {
		// hide
	}
}
